<template>
	<el-dialog v-model="visible" :title="!dataForm.field ? '新增' : '修改'" :close-on-click-modal="true" draggable>
		<el-form ref="dataFormRef" :model="dataForm" :rules="dataRules" label-width="120px">
			<el-form-item prop="field" label="基金名称">
				<el-input v-model="dataForm.field" :disabled="fieldDisabled" placeholder="基金名称"></el-input>
			</el-form-item>
			<el-form-item prop="code" label="基金代码">
				<el-input v-model="dataForm.code" placeholder="基金代码"></el-input>
			</el-form-item>
		</el-form>
		<template #footer>
			<el-button @click="restForm()">取消</el-button>
			<el-button type="primary" @click="submitHandle()">确定</el-button>
		</template>
	</el-dialog>
</template>

<script setup lang="ts">
import { reactive, ref, nextTick } from 'vue'
import { ElMessage } from 'element-plus/es'
import { postFund } from '@/api/fund/index'

const emit = defineEmits(['refreshDataList'])

const visible = ref(false)
const fieldDisabled = ref(false)
const dataFormRef = ref()

const dataForm = reactive({
	field: '',
	code: ''
})

//初始化组件
const init = (field?: string, code?: string) => {
	visible.value = true
	dataForm.field = ''
	dataForm.code = ''

	// 重置表单数据
	if (dataFormRef.value) {
		dataFormRef.value.resetFields()
	}

	//在Mounted周期后赋值，防止resetFields()重置的初始值为第一次挂载赋值的值
	nextTick(() => {
		if (field) {
			dataForm.field = field
			fieldDisabled.value = true
		}

		if (code) {
			dataForm.code = code
		}
	})
}

//表单校验规则
const dataRules = ref({
	field: [{ required: true, message: '必填项不能为空', trigger: 'blur' }],
	code: [{ required: true, message: '必填项不能为空', trigger: 'blur' }]
})

//重置表单
const restForm = () => {
	dataForm.field = ''
	dataForm.code = ''
	dataFormRef.value.resetFields()
	visible.value = false
}

// 表单提交
// const submitHandle = () => {
// 	dataFormRef.value.validate((valid: boolean) => {
// 		if (!valid) {
// 			return false
// 		}
// 		dataForm.menuIdList = [...menuListTree.value.getHalfCheckedKeys(), ...menuListTree.value.getCheckedKeys()]

// 		useRoleSubmitApi(dataForm).then(() => {
// 			ElMessage.success({
// 				message: '操作成功',
// 				duration: 500,
// 				onClose: () => {
// 					visible.value = false
// 					emit('refreshDataList')
// 				}
// 			})
// 		})
// 	})
// }

//提交表单
const submitHandle = () => {
	dataFormRef.value.validate((valid: boolean) => {
		if (!valid) {
			return false;
		}
		postFund({ key: dataForm.field, value: dataForm.code }).then((res) => {
			ElMessage.success({
				message: '操作成功',
				duration: 500,
				onClose: () => {
					visible.value = false
					emit('refreshDataList')
				}
			})
		})
	})
}

defineExpose({
	init
})
</script>
